package com.zlzlib.libnetty.tcp.handler;


import com.zlzlib.libnetty.base.BaseClient;
import com.zlzlib.libnetty.util.Util;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by zlz on 2019/11/19.
 * 握手认证消息响应处理handler
 */
public class LoginAuthRespHandler<T> extends ChannelInboundHandlerAdapter {

    private final BaseClient<T> imsClient;

    public LoginAuthRespHandler(BaseClient<T> imsClient) {
        this.imsClient = imsClient;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        T msg =  imsClient.getDataListener().changeMsgData(obj);
        if (imsClient.getDataListener().isDataEmpty(msg)) {
            return;
        }
        if (imsClient.getDataListener().isHandshakeMsg(msg)) {
            Util.logInfo("收到服务端握手响应消息，message=" + msg);
            if (imsClient.getDataListener().isHandshakeSuccess(msg)) {
                // 握手成功，马上先发送一条心跳消息，至于心跳机制管理，交由HeartbeatHandler
                T heartbeatMsg = imsClient.getDataListener().getHeartbeatMsg();
                if (imsClient.getDataListener().isDataEmpty(heartbeatMsg)) {
                    return;
                }
                // 握手成功，检查消息发送超时管理器里是否有发送超时的消息，如果有，则全部重发
                imsClient.getMsgTimeoutTimerManager().onResetConnected();
                Util.logInfo("发送心跳消息：" + heartbeatMsg + "当前心跳间隔为："
                        + imsClient.getHeartbeatInterval() + "ms");
                imsClient.sendMsg(heartbeatMsg);
                // 添加心跳消息管理handler
                imsClient.addHeartbeatHandler();
            } else {
                // 握手失败，触发重连
                imsClient.resetConnect();
            }
        } else {
            // 消息透传
            ctx.fireChannelRead(msg);
        }
    }

}
